#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "tmf\fn_execHC.sqf"
#include <tmf_constants.h>
#include <tmf_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;

if (((isNil QGVAR(INITIALIZED)) || {!GVAR(INITIALIZED)}) && {time < 10}) exitWith {
	// Case when we are less than X seconds from start, so HC had no time to connect
	DEBUG_1("Delaying execution");
	_this spawn {
		sleep (10 - time);
		_this call FFUNC(execHC);
	};
};

private ["_params","_script","_i","_is_fnc","_hc_id","_fnc"];
_params = [];
_script = "";
if (IS_STRING(_this)) then {
	_script = _this;
} else {
	if (IS_ARRAY(_this) && {count _this > 0}) then {
		if (IS_STRING((_this select (count _this - 1)))) then {
			_script = (_this select (count _this - 1));
			if (count _this > 1) then {
				if (count _this == 2 && {IS_ARRAY((_this select 0))}) then {
					_params = _this select 0;
				} else {
					for "_i" from 0 to (count _this - 2) do {
						_params set [count _params, _this select _i];
					};
				};
			};
		};
	};
};
if (_script != "") then {
	_is_fnc = !(isNil _script);
	_hc_id = 0 call MCFUNC(getHC);
	if (_hc_id >= 0 && !(0 call MCFUNC(isHC))) then {
		DEBUG_1("HC Execute",_hc_id);
		[QGVAR(hc_execute),[_params,_script,_hc_id]] call FFUNC(callevent);
	} else {
		if (!isDedicated && hasInterface) then {
			DEBUG_1("Player called",_hc_id);
			[QGVAR(s_execute),[_script,_params]] call FFUNC(callevent);
		} else {
			DEBUG_1("Local Execute",_is_fnc);
			// Already on a HC or no HC
			if (_is_fnc) then {
				_fnc = (missionNameSpace getVariable [_script,""]);
				if (IS_STRING(_fnc)) then {
					_fnc = call compile _script;
				};
				_params spawn _fnc;
			} else {
				_params execVM _script;
			};
		};
	};
};

TRACE("End");
TMFPROFILERSTOP;